# -*- coding: utf-8 -*-
__author__ = 'bobby'

from bs4 import BeautifulSoup
from urllib.request import urlopen
import requests
try:
    import cookielib
except:
    import http.cookiejar as cookielib

import re
import time
import json

session = requests.session()
session.cookies = cookielib.LWPCookieJar(filename="cookies.txt")
try:
    session.cookies.load(ignore_discard=True)
except:
    print("cookie未能加载")
agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8'
header = {
    "HOST":"www.zhihu.com",
    "Referer": "https://www.zhizhu.com",
    'User-Agent': agent
}

def is_login():
    #通过个人中心页面返回状态码来判断是否为登录状态
    inbox_url = "https://www.zhihu.com/inbox"
    #allow_redirects为检测是否重定向
    response = session.get(inbox_url, headers=header, allow_redirects=False)
    if response.status_code  != 200:
        return False
    else:
        return True

def get_xsrf():
    #获取xsrf code
    response = session.get("https://www.zhihu.com", headers=header)
    soup = BeautifulSoup(response.text, 'html.parser')
    data = soup.find('div', attrs={'id': 'data'})['data-state']
    data = json.loads(data)

    xsrf = data['token']['xsrf']
    return "xsrf"

def get_index():
    response = session.get("https://www.zhihu.com", headers=header)
    with open("index_page.html", "wb") as f:
        f.write(response.text.encode("utf-8"))
    print ("ok")


def get_captcha():
    # 验证码URL是按照时间戳的方式命名的
    captcha_url = 'https://www.zhihu.com/captcha.gif?r=%d&type=login&lang=cn' % (int(time.time() * 1000))
    print(captcha_url)
    response = session.get(captcha_url, headers=header)
    # 保存验证码到当前目录
    print(response.content)
    with open('captcha.gif', 'wb') as f:
        f.write(response.content)
        f.close()

    # 自动打开刚获取的验证码
    from PIL import Image
    try:
        img = Image.open('captcha.gif')
        img.show()
        img.close()
    except:
        pass

    captcha = {
        'img_size': [200, 44],
        'input_points': [],
    }
    points = [[22.796875, 22], [42.796875, 22], [63.796875, 21], [84.796875, 20], [107.796875, 20], [129.796875, 22],
              [150.796875, 22]]
    seq = input('请输入倒立字的位置\n>')
    for i in seq:
        captcha['input_points'].append(points[int(i) - 1])
    json.dumps(captcha)


def zhihu_login(account, password):
    #知乎登陆
    if re.match("1\d{10}",account):
        print("手机号码登陆")
        port_url = "https://www.zhihu.com/login/phone_num"
        port_data ={
            'captcha_type': 'cn',
            '_xsrf': get_xsrf(),
            'phone_num': account,
            'password': password,
            'captcha': get_captcha(),
        }
    else:
        if "@" in account:
            #判断用户名是否为邮箱
            print("邮箱方式登录")
            post_url = "https://www.zhihu.com/login/email"
            post_data = {
                'captcha_type': 'cn',
                '_xsrf': get_xsrf(),
                'email': account,
                'password': password,
                'captcha': get_captcha(),
            }

    response_text = session.post(port_url, data=port_data, headers=header)
    response_text = json.loads(response_text.text)
    if 'msg' in response_text and response_text['msg'] == '登录成功':
        print('登录成功！')
    else:
        print('登录失败')

    session.cookies.save()
# get_index()
zhihu_login("18027359048","@Hua28252286")
is_login()